/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-03-02 21:59:13
 */
import throttle, { DebouncedFunc } from '@/utils/tools/throttle'
import { isNil, map } from 'ramda'
import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators'
import store from '@/store'
import { RoleState } from '@/views/system/role/uilts'
type Func = DebouncedFunc<(params: ObjectMap, options?: ObjectMap) => Promise<any>>
let getClassifyListFunc: Func
let getRoleFunc: Func
let getSeriesListFunc: Func
export interface Options {
	value: string | number
	label: string
	type?: number
	title?: string
	[index: string]: any
	children?: Array<this>
	isLeaf?: boolean
	loading?: boolean
}
export interface BasicDataState {
	classifyList: Array<Options>
	roleList: Array<Options>
}

@Module({ namespaced: true, store, name: 'basicData', dynamic: true })
export class BasicData extends VuexModule implements BasicDataState {
	/** 商家 */
	public classifyList: Array<Options> = []
	/** 角色 */
	public roleList: Array<Options> = []
	/** 系列 */
	public seriesList: Array<Options> = []
	/** 获取分类数据 */
	@Action
	public async getClassifyList(params = {}) {
		if (isNil(getClassifyListFunc)) {
			// 防抖
			// getClassifyListFunc = throttle(API.server.storeGoods.getCatList.request)
		}
		const { success, data } = await getClassifyListFunc(params)
		if (success && !isNil(data)) {
			this.SET_CLASSIFYLIST(data)
		}
	}
	/** 修改分类数据 */
	@Mutation
	private SET_CLASSIFYLIST(data: readonly any[]) {
		this.classifyList = map((res) => {
			return {
				...res,
				label: res.name as string,
				value: res.id,
			}
		}, data) as Options[]
	}
	/** 获取角色 */
	@Action
	public async getRoleList() {
		if (isNil(getRoleFunc)) {
			// 防抖
			getRoleFunc = throttle(API.server.role.getRolePage.request)
		}
		const { success, data } = await getRoleFunc({ size: 999, current: 1 })
		if (success && !isNil(data) && !isNil(data.data)) {
			this.SET_GETROLELIST(data.data)
		}

	}
	/** 获取角色 */
	@Mutation
	private SET_GETROLELIST(data: RoleState[]) {
		this.roleList = map((res) => {
			return {
				...res,
				label: res.rolename as string,
				value: res.id as number,
			}
		}, data)
	}
	/** 获取分类数据 */
	@Action
	public async getSeriesList(params = { pageSize: 99999 }) {
		if (isNil(getSeriesListFunc)) {
			// 防抖
			// getSeriesListFunc = throttle(API.server.storeStoreCat.getList.request)
		}
		const { success, data } = await getSeriesListFunc(params)
		if (success && !isNil(data?.data)) {
			this.SET_SERIESLIST(data?.data)
		}
	}
	/** 修改分类数据 */
	@Mutation
	private SET_SERIESLIST(data: readonly any[]) {
		this.seriesList = map((res) => {
			return {
				...res,
				label: res.name as string,
				value: res.id,
			}
		}, data) as Options[]
	}
}

export const BasicDataModule = getModule(BasicData)
